package ym.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ym.mapper.RoleMapper;
import ym.pojo.Role;
import ym.pojo.RolePermission;
import ym.service.AdminRoleService;
import ym.service.RolePermissionService;
import ym.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleService adminRoleService;
    @Autowired
    private RolePermissionService rolePermissionService;

    @Override
    public void add(Role role) {
        roleMapper.insert(role);
    }

    @Override
    public void update(Role role) {
        roleMapper.updateById(role);
    }

    @Override
    public void delete(Integer id) {
        // 删除角色
        roleMapper.deleteById(id);
        // 删除用户_角色中间表的相关数据
        adminRoleService.deleteByRoleId(id);
        // 删除角色_权限中间表的相关数据
        rolePermissionService.deleteByRoleId(id);

    }

    @Override
    public Role findById(Integer id) {
        return roleMapper.findById(id);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.selectList(null);
    }

    @Override
    public Page<Role> search(int page, int size) {
        return roleMapper.selectPage(new Page(page, size), null);
    }

    @Override
    public void updatePermission(Integer roleId, Integer[] permissionIds) {
        // 删除角色的所有权限
        rolePermissionService.deleteByRoleId(roleId);
        // 给角色添加权限
        for (Integer permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionService.add(rolePermission);
        }
    }
}
